import requests
import json
import time


class FeishuClient:
    def __init__(self):
        self.app_id = "cli_a8bcd0d366d9900c"
        self.app_secret = "XfetMPDN3BBDiuNLy5JsSgHsnrEjIcZq"
        self.chat_id = "oc_4757cfb971d94b1252fbc55add538fd6"  # 质量信息推送群chat_id
        self.tenant_access_token = None
        self.expire_time = 0

    def get_tenant_access_token(self):
        """获取tenant_access_token，自动处理过期问题"""
        # 检查token是否过期，提前100秒刷新
        if self.tenant_access_token and self.expire_time - time.time() > 100:
            print(f"expire_timme:{self.expire_time}")
            return self.tenant_access_token

        # 调用飞书API获取token
        url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
        headers = {"Content-Type": "application/json; charset=utf-8"}
        data = {"app_id": self.app_id, "app_secret": self.app_secret}

        try:
            response = requests.post(url, headers=headers, data=json.dumps(data))
            response.raise_for_status()  # 检查请求是否成功
            result = response.json()

            if result.get("code") == 0:
                self.tenant_access_token = result.get("tenant_access_token")
                self.expire_time = time.time() + result.get("expire", 0)
                return self.tenant_access_token
            else:
                print(f"获取tenant_access_token失败: {result.get('msg')}")
                return None

        except requests.exceptions.RequestException as e:
            print(f"网络请求错误: {e}")
            return None

    def send_message_to_user(self, user_id, content):
        """发送文本消息到指定群组"""
        token = self.get_tenant_access_token()
        if not token:
            print("无法获取有效的访问令牌")
            return False

        url = "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=user_id"
        headers = {
            "Content-Type": "application/json; charset=utf-8",
            "Authorization": f"Bearer {token}",
        }
        data = {
            "receive_id": user_id,
            "msg_type": "text",
            "content": json.dumps({"text": content}),
        }

        try:
            response = requests.post(url, headers=headers, data=json.dumps(data))
            response.raise_for_status()
            result = response.json()

            if result.get("code") == 0:
                print(f"消息发送成功，message_id: {result.get('data', {}).get('message_id')}")
                return True
            else:
                print(f"消息发送失败: {result.get('msg')}")
                return False

        except requests.exceptions.RequestException as e:
            print(f"网络请求错误: {e}")
            return False

    def send_message(self, content):
        """发送文本消息到指定群组"""
        token = self.get_tenant_access_token()
        if not token:
            print("无法获取有效的访问令牌")
            return False

        url = "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=chat_id"
        headers = {
            "Content-Type": "application/json; charset=utf-8",
            "Authorization": f"Bearer {token}",
        }
        data = {
            "receive_id": self.chat_id,
            "msg_type": "text",
            "content": json.dumps({"text": content}),
        }

        try:
            response = requests.post(url, headers=headers, data=json.dumps(data))
            response.raise_for_status()
            result = response.json()

            if result.get("code") == 0:
                print(f"消息发送成功，message_id: {result.get('data', {}).get('message_id')}")
                return True
            else:
                print(f"消息发送失败: {result.get('msg')}")
                return False

        except requests.exceptions.RequestException as e:
            print(f"网络请求错误: {e}")
            return False


xiaozhi = FeishuClient()
